package org.geekbang.thinking.in.spring.conversion;

import java.beans.PropertyEditor;
import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.io.StringReader;
import java.util.Map;
import java.util.Properties;

/**
 *
 * 将 String 转换成 Properties
 * @author : zjj
 * @date : 2022/3/7 14:49
 */
public class StringToPropertiesPropertyEditor extends PropertyEditorSupport implements PropertyEditor {
    // 1 实现 setAsText 方法
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        // 2  将String 转成 Properties
        Properties properties = new Properties();
        try{
            properties.load(new StringReader(text));
        }catch (IOException e){
            throw new IllegalArgumentException(e);
        }

        // 3 临时存储 properties对象
        setValue(properties);
        // next 获取临时 properties对象 #getValue();

    }
    // 尽量还原传入的 text
    @Override
    public String getAsText() {
        Properties properties = (Properties) getValue();

        StringBuilder textBuilder = new StringBuilder();
        for (Map.Entry<Object,Object> entry : properties.entrySet()) {
            textBuilder.append(entry.getKey())
                    .append("=")
                    .append(entry.getValue())
                    .append(System.getProperty("line.separator"));
        }

        return textBuilder.toString();
    }
}
